import React, { FC, memo, ReactNode, useEffect } from 'react'
import { FormInstance, Input } from 'antd'
import dayjs from 'dayjs'
import confirmModal from '@/utils/confirm-modal'
import { ActionDesc } from '@/global/constant'
import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'
import VerifyCodeButton from '@/components/verify-code-button'
import usePageSearch from '@/hooks/use-page-search'
import usePageContent from '@/hooks/use-page-content'
import usePageModal from '@/hooks/use-page-modal'
import {
  fetchPageAddOrEditAction,
  fetchPageDeleteAction
} from '@/store/module/main/page-common'
import activityListContent from './config/activitylist-content'
import activityListSearch from './config/activitylist-search'
import getActivityListModalAddOrEdit from '@/views/main/c-views/activity/activity-list/config/actiivitylist-modal-add-or-edit'

interface IProps {
  children?: ReactNode
}

const inputWithVerifyCodeStyle = {
  display: 'flex',
  alignItems: 'center'
}
const ActivityList: FC<IProps> = (props) => {
  // 引入搜索、内容、弹框相关的hook
  const { pageContentRef, searchClick, resetClick } = usePageSearch()
  const { pageModalRef, onModalOk, onModalCancel, getCodeClick } = usePageModal(
    { okCb, cancelCb, afterCloseResetStatusCb }
  )
  const {
    modal: [curModalConfig, setCurModalConfig],
    record: [currentRecord, setCurrentRecord],
    dispatch,
    toSecondAuth,
    handleSecondAuth
  } = usePageContent({ pageModalRef })

  // modal的确定按钮
  function afterCloseResetStatusCb() {
    // ！！！这一步非常关键，我们希望每次点击确认后要销毁这个modal框的状态，
    // 但是只有modal的配置发生改变才会重新渲染这个modal组件
    // 假如我们两次点击二次认证框，但是我们希望下一次进去消除上一次残留的状态，就要让他的配置发生改变，所以这里改为空
    // setCurModalConfig({})
    setCurModalConfig({})
  }

  function cancelCb() {
    setCurModalConfig({})
  }

  async function okCb(form: FormInstance | undefined) {
    // 获取当前配置的信息，看一下是属于什么类型的表单描述
    const { desc } = curModalConfig.formProps
    // 获取表单数据
    const values = form?.getFieldsValue()
    if (desc === ActionDesc.SecondAuth) {
      /** 1、当前描述为：二次认证 **/
      return toSecondAuth(values)
    } else if (desc === ActionDesc.Add) {
      /**  2、新增  **/
      return await toAddOrEdit(values, true)
    } else if (desc === ActionDesc.Edit) {
      /**  3、编辑  **/
      return await toAddOrEdit(values, false)
    }
  }

  // 通用：处理“编辑”的回显数据的，只要config一改变，就手动设置初始值
  useEffect(() => {
    if (curModalConfig?.formProps?.desc === ActionDesc.Edit) {
      const { activityName, activityBeginTime, activityEndTime } = currentRecord
      // 整理表单参数
      const form = pageModalRef.current?.getFormInstance()
      form?.setFieldsValue({
        activityName,
        activityBeginTime: dayjs(activityBeginTime),
        activityEndTime: dayjs(activityEndTime)
      })
    }
  }, [curModalConfig])

  // 通用：按钮的操作---这里能进行任意按钮的操作
  async function actionClick(key: any, record?: any) {
    // 设置当前行数据：如果是批量操作和新增就没有record也要设置，表明是空状态
    // 这样做可以避免，先点修改再点增加，要把修改后残留的id去掉，否则新增也会带上id
    setCurrentRecord(record)
    // 操作类型
    if (key === ActionDesc.Add) {
      // 新增
      const config = getActivityListModalAddOrEdit(true)
      setCurModalConfig(config)
      pageModalRef.current?.openModal()
    } else if (key === ActionDesc.Edit) {
      // 修改
      const config = getActivityListModalAddOrEdit(false)
      setCurModalConfig(config)
      pageModalRef.current?.openModal()
    } else if (key === ActionDesc.Delete) {
      // 单删除
      handleSecondAuth(() => {
        confirmModal('是否删除该数据?').then(() =>
          dispatch(fetchPageDeleteAction(record.activityId))
        )
      })
    }
  }

  // 新增或者修改， 参数2：true -> 新增
  async function toAddOrEdit(values: any, isAdd: boolean) {
    const { activityName, activityBeginTime, activityEndTime } = values
    // 整理参数：将默认的表单格式转成 YYYY-MM-DD HH:mm:ss
    const newActivityBeginTime = dayjs(activityBeginTime).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    const newActivityEndTime = dayjs(activityEndTime).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    // 新的请求参数
    const params = {
      activityName,
      activityBeginTime: newActivityBeginTime,
      activityEndTime: newActivityEndTime
    }
    // 发请求
    return dispatch(
      fetchPageAddOrEditAction({
        params: {
          ...params,
          ...(currentRecord && { activityId: currentRecord.activityId })
        },
        isAdd,
        isNeedEncrypt: false
      })
    )
  }

  return (
    <>
      <PageSearch
        config={activityListSearch}
        searchClick={searchClick}
        resetClick={resetClick}
      ></PageSearch>
      <PageContent
        ref={pageContentRef}
        config={activityListContent}
        actionClick={actionClick}
      ></PageContent>
      <PageModal
        ref={pageModalRef}
        modalConfig={curModalConfig}
        onOk={onModalOk}
        onCancel={onModalCancel}
      >
        <div key="code" style={inputWithVerifyCodeStyle}>
          <Input name="code" />
          <VerifyCodeButton onClick={getCodeClick} />
        </div>
      </PageModal>
    </>
  )
}

export default memo(ActivityList)
